package com.controller;

import com.Util.*;
import com.Util.serviceUtil.TransUntil;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;




import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.io.File;


import static com.Util.UtilBase.*;

/**
 * 查询专用接口
 */
@Path ( "blog" )
public class BlogController extends BaseController {


//    /**
//     * 数据信息
//     * @param query
//     * @return
//     */
//    @POST
//    @Path ( "search_train" )
//    @Produces(MediaType.APPLICATION_JSON+";charset=utf-8")
//    @Consumes(MediaType.APPLICATION_JSON)
//    public String serchTrain(String query){
//        try(Connection conn= DB.getConnection ();
//            DSLContext create= DSL.using ( conn, SQLDialect.MYSQL )) {
//            //接收参数
//            this.jsonObject=new JsonParser ().parse ( query ).getAsJsonObject ().get ( "query" ).getAsJsonObject ();
//            //获取userId
//            String userId=getJsonAsString ( this.jsonObject,"userId" );
//            Integer currentPage=this.jsonObject.get ( "page" ).getAsInt ();
//            Integer pageSize=this.jsonObject.get ( "pagenum" ).getAsInt ();
//            Integer type=this.jsonObject.get ( "type" ).getAsInt ();
//            String keyword=this.jsonObject.get ( "keyword" ).getAsString ();
//            //查询开始
//            if (userId==null || userId.equals ( "".trim () )){
//                return error ( -1,"没有登录" );
//            }
//            Result<Record> records=create.select (  )
//                    .from ( TRAIN_NAME )
//                    .where ( TRAIN_NAME.TYPE.eq ( type ) )
//                    .and ( TRAIN_NAME.NAME.like ( "%"+keyword+"%" ) )
//                    .limit ( pageSize )
//                    .offset ( (currentPage-1)*pageSize )
//                    //.fetchInto ( TrainNameRecord.class );
//            .fetch ();
//            JsonArray jsonArray=dataChangeJsonArray ( records );
//            Result<Record> recordCounts=create.select (  )
//                    .from ( TRAIN_NAME )
//                    .where ( TRAIN_NAME.TYPE.eq ( type ) )
//                    .and ( TRAIN_NAME.NAME.like ( "%"+keyword+"%" ) )
//                    .fetch ();
//            Integer count=dataChangeJsonArray ( recordCounts ).size ();
//            JsonObject jsonObject=new JsonObject ();
//            jsonObject.addProperty ( "count",count );
//            jsonObject.add ( "detail",jsonArray );
//            return success (jsonObject);
//        }catch (Exception e){
//            e.printStackTrace ();
//            return error ( -1,"请联系管理员" );
//        }
//
//    }
//
//    /**
//     * 增加search
//     * @param query
//     * @return
//     */
//    @POST
//    @Path ( "add_search" )
//    @Produces(MediaType.APPLICATION_JSON+";charset=utf-8")
//    @Consumes(MediaType.APPLICATION_JSON)
//    public String addSearch(String query){
//        try(Connection conn= DB.getConnection ();
//            DSLContext create= DSL.using ( conn, SQLDialect.MYSQL )) {
//            this.jsonObject=new JsonParser ().parse ( query ).getAsJsonObject ().get ( "query" ).getAsJsonObject ();
//            Integer type=getJsonAsInt ( this.jsonObject,"type" );
//            String name=getJsonAsString ( this.jsonObject,"name" );
//            //先判断是否存在
//            Record record=create.fetchOne ( TRAIN_NAME,TRAIN_NAME.NAME.eq ( name ).and ( TRAIN_NAME.TYPE.eq ( type ) )  );
//            if (record!=null){
//                //已经存在
//                return error ( -1,"此公司已经存在，你个智障，看清楚在输入，在乱输，就把赵为永送给你了" );
//            }
//            TrainNameRecord nameRecord=create.newRecord ( TRAIN_NAME );
//            nameRecord.setName ( name );
//            nameRecord.setType ( type );
//            nameRecord.insert ();
//        }catch (Exception e){
//            e.printStackTrace ();
//            return error (  );
//        }
//        return success ("ok");
//    }

    /**
     * 测试base64图片的上传
     * @param query
     * @return
     */
    @POST
    @Path ( "img_base64" )
    @Produces(MediaType.APPLICATION_JSON+";charset=utf-8")
    @Consumes(MediaType.APPLICATION_JSON)
    public String testImgUpload(String query){
        JsonObject jsonObject=new JsonParser ().parse ( query ).getAsJsonObject ().get ( "query" ).getAsJsonObject ();
        String img=getJsonAsString ( jsonObject,"img" );
        //初始化路径
        String path=req.getSession ().getServletContext ().getRealPath ( "upload" );
        //重新命名的图片
        String postfixName="/"+System.currentTimeMillis ()/1000+".jpg";
        //判断路径是否存在，不存在，就新建
        File file=new File ( path );
        if(!file.exists ()){
            file.mkdirs ();
        }
        //开始装换图片
        Boolean isSuccess= null;
        File newImgFile=null;
        try {
            isSuccess = Base64Until.generateImage ( img,path+postfixName);
            if (isSuccess){
                newImgFile=new File ( path+postfixName );
                //存入阿里的OSS
                String url= FileUntil.upload ( newImgFile,true );
                return success (Config.OSS+url);
            }
            return error (-1,"你需要装换的可能不是图片");
        } catch (Exception e) {
            e.printStackTrace ();
            return error ( -1,"图片装换失败请联系管理员" );
        }finally {
            //删除原图片
            newImgFile.delete ();
        }

    }

   /* *//**
     * 统一为网站会员发送邮件
     * @param query
     * @return
     *//*
    @POST
    @Path ( "mail_send" )
    @Produces(MediaType.APPLICATION_JSON+";charset=utf-8")
    @Consumes(MediaType.APPLICATION_JSON)
    public String mailSend(String query) {
        try (Connection conn = DB.getConnection ();
             DSLContext create = DSL.using ( conn, SQLDialect.MYSQL )) {

            JsonObject jsonObject=new JsonParser ().parse ( query ).getAsJsonObject ().get ( "query" ).getAsJsonObject ();
            //创建事务
            create.transaction ( configuration -> {
                //读取数据
               // JsonObject jsonObject=new JsonParser ().parse ( query ).getAsJsonObject ().get ( "query" ).getAsJsonObject ();

                String subject=getJsonAsString ( jsonObject,"subject" );
                String content=getJsonAsString ( jsonObject,"content" );
                //获取网站所有注册用户的邮箱
               // StringBuilder sql=new StringBuilder (  );
                Result<Record> records=create.select (  ) .from ( MTO_USERS ).fetch ();
                JsonArray jsonArray=dataChangeJsonArray ( records );
                //log.info ( "【数据信息】={}",jsonArray.toString () );
                //循环开始
                for (int i = 0; i <jsonArray.size () ; i++) {
                  String email= jsonArray.get ( i ).getAsJsonObject ().get ( "email" ).getAsString ();
                    //获取每个人的邮箱
                    MailUtil.mailSend ( email,subject,"" );
                }
            });
            return success ("发送完成");

        } catch (Exception e) {
            //e.printStackTrace ();
            return error ( -1,"请联系管理员" );
        }
    }*/

   /* *//**
     * 将注册信息导入到Excel表格
     * @param query
     * @return
     *//*
    @POST
    @Path ( "upload_excel" )
    @Produces(MediaType.APPLICATION_JSON+";charset=utf-8")
    @Consumes(MediaType.APPLICATION_JSON)
    public String uploadExcel(String query){
        File file=null;
        try(Connection conn = DB.getConnection ();
            DSLContext create = DSL.using ( conn, SQLDialect.MYSQL )) {
            //事务开始
           //  String url="";
       // create.transaction ( configuration -> {
            //查询出网站的所有的注册的用户
            List<UserDto> result=create.select ( ).from ( MTO_USERS )
                    .fetch ().into ( UserDto.class );

            log.info ( "【数据信息】={}",result );
            //封装数据开始
            //JsonArray users=dataChangeJsonArray ( result );
            //开始测试分装数据
            *//**
             * 1.创建对象
             * 2.循环传值
             * 3.开始测试
             *//*
            //创建list集合
           *//* List<UserDto> userDtos=new ArrayList<> (  );
            for (int i = 0; i <users.size () ; i++) {
                jsonObject=users.get ( i ).getAsJsonObject ();
                UserDto userDto=new UserDto ();
                userDto.setCreateTime ( new Date (  ).toString () );
                userDto.setId ( getJsonAsString ( jsonObject,"id") );
                userDto.setName ( getJsonAsString ( jsonObject,"name" ) );
                userDtos.add ( userDto );
            }*//*
            //构建文件零时路径
            String path=req.getSession ().getServletContext ().getRealPath ( "excel" );
             file=new File ( path );
            if (!file.exists ()){
                file.mkdirs ();
            }
            String newPath;
            newPath=String.format ("/register_user_%tF.xls", new Date (  ) );
            log.info ( "文件全路径={}",path+newPath );
            ExcelHelper.dto2Excel ( result,path+newPath,"注册用户表" );
            //存入阿里oss
            file=new File (path+newPath);
            String url=FileUntil.upload ( file,false);

      //  } );
            return success (Config.OSS+url);
        }catch (Exception e){
            e.printStackTrace ();
            return error (-1,e.getMessage ());
        }finally {
            file.delete ();
        }
    }*/
    /**
     * 翻译专用
     * @param query
     * @return
     */
    @POST
    @Path ( "translate" )
    @Produces(MediaType.APPLICATION_JSON+";charset=utf-8")
    @Consumes(MediaType.APPLICATION_JSON)
    public String translate(String query){
        try {
            //获得参数
            //JsonObject jsonObject = new JsonParser ().parse ( query ).getAsJsonObject ();
            JsonObject jsonObject=new JsonParser ().parse ( query ).getAsJsonObject ();
            String param = getJsonAsString ( jsonObject, "query" );
            String from = getJsonAsString ( jsonObject, "from" );
            String to = getJsonAsString ( jsonObject, "to" );
            //调用方法
            JsonArray result = TransUntil.getResult ( param, from, to );
            JsonObject object=result.get ( 0 ).getAsJsonObject ();
            return success (object);
        }catch (Exception e){
            e.printStackTrace ();
            return error ( -1,e.getMessage ());
        }
    }



}
